<template>
  <div class="homeview">
    <!-- 搜索 -->
    <div class="row d-0 m-0 mt-4" style="width: 100%">
      <div class="col-12 d-0 m-0 d-flex justify-content-center" style="width: 100%">
        <div class="input-group searchField">
          <input
            v-model="searchParams.searchText"
            type="text"
            class="form-control"
            @keyup.enter="doSearch"
            placeholder="请输入查询参数"
            style="border-radius: 2rem 0 0 2rem"
          />
          <div class="input-group-append">
            <button type="button" class="btn input-group-text" @click="doSearch">
              <i class="bi bi-search"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
    <!--这是分类 -->
    <a-tabs
      v-model:activeKey="selectedCategory"
      size="middle"
      style="margin-left: 2vw"
      @change="doSearch"
    >
      <a-tab-pane key="all" tab="全部" />
      <a-tab-pane v-for="category in categoryList" :tab="category" :key="category" />
    </a-tabs>
    <!--这是标签 -->
    <div class="tag-bar" style="margin-bottom: 6vh; margin-left: 2vw">
      <a-space :size="[16, 8]" wrap>
        <a-checkable-tag
          v-for="(tag, index) in tagList"
          :key="tag"
          v-model:checked="selectedTags[index]"
          @change="doSearch"
        >
          {{ tag }}
        </a-checkable-tag>
      </a-space>
    </div>
    <div ref="containerRef" class="waterfall-container">
      <!-- 添加更多属性控制瀑布流布局，使其更好地响应屏幕大小 -->
      <!-- 设置最小宽度和间距 -->
      <Waterfall
        :list="dataList"
        :cross-origin="false"
        background-color="none"
        :min-width="250"
        :gutter="15"
      >
        <template #item="{ item: picture, index }">
          <div class="card roleimg">
            <LazyImg class="card_img" :url="picture.url" @click="handleCLick(picture.id)" />
            <div
              class="pictureName"
              style="padding: 2px 8px 2px 8px; text-align: left; font-size: 12px; font-weight: bold"
            >
              {{ picture.pictureName }}
            </div>
            <div
              v-if="picture.introduction"
              class="description"
              style="padding: 0px 8px 0px 8px; text-align: left; font-size: small"
            >
              {{ picture.introduction }}
            </div>
            <div class="tagdisplay" style="padding: 5px; white-space: pre-wrap">
              <a-tag color="green"> {{ picture.category ?? '默认' }}</a-tag>
              <a-tag v-for="tag in picture.tags" :key="tag"> {{ tag }}</a-tag>
            </div>
          </div>
        </template>
      </Waterfall>
      <div v-if="fetchingMore" class="loading-indicator">
        <a-space>
          <a-spin size="small" style="color: yellow" />
          <a-spin />
          <a-spin size="large" />
        </a-space>
      </div>
    </div>
  </div>
</template>
<script setup>
import { LazyImg, Waterfall } from 'vue-waterfall-plugin-next'
import 'vue-waterfall-plugin-next/dist/style.css'
import { onMounted, reactive, ref, nextTick } from 'vue'
import { getPicturePageVOs, getTagsAndCategory } from '@/api/picture.js'
import { message } from 'ant-design-vue'
import { useInfiniteScroll } from '@vueuse/core'
import router from '@/router/index.js'

//瀑布流组件的数据
const dataList = ref([])
const loading = ref(true) //这个加载没啥用可以删除，保留是用于一些加载组件的，确实没用
const fetchingMore = ref(false)
const canLoadMore = ref(true)
let containerRef = ref(null)

//处理点击图片的操作
const handleCLick = (id) => {
  router.push({
    path: `/picture/details/${id}`,
  })
}

//给分类和标签的框添加样式，使用hasAdd来保证仅执行一次
const hasAdd = ref(false)
const addElementForTagsCate = () => {
  if (hasAdd.value) return
  var btnElement = document.createElement('button')
  btnElement.innerHTML = '大家好'
  var parentElement = document.getElementsByClassName('ant-tabs-tab-btn')

  for (var arrElement of parentElement) {
    var oldContent = arrElement.innerHTML
    arrElement.innerHTML = `<button type="button"
    class="btn btn-primary"
    style="background: linear-gradient(135deg, #00EBFF 0%, #00EBFF 20.32%, #8972FF 80.02%, #AE8DFF 100%);
    border-radius: 20px;
    border: 0.01rem outset white;
    "
 >${oldContent}</button>`
  }
  hasAdd.value = true
}

//分类和标签组件的数据
const categoryList = ref([])
const tagList = ref([])
const selectedCategory = ref('all') //分类当前选了哪个
const selectedTags = ref([])

//这里是对上面的antdv里的tabs标签的内容做更改（把普通的文本替换为按钮）
const getTagsCate = async () => {
  try {
    const res = await getTagsAndCategory()
    if (res.data.code === 0 && res.data.data) {
      tagList.value = res.data?.data?.tagList ?? []
      categoryList.value = res.data?.data?.categoryList ?? []
      setTimeout(() => {
        addElementForTagsCate()
      }, 20)
    } else {
      message.error('出错了，原因：' + res.data.message)
    }
  } catch (e) {
    message.error('出错了，请刷新重试，原因：' + e.message)
  }
}
//当标签或者分类发生变化时，重新操作
const doSearch = async () => {
  //搜索前数据初始化
  fetchingMore.value = false
  canLoadMore.value = true
  dataList.value = []
  searchParams.current = 1
  // 初始加载第一页数据
  await pullPagesVO()

  // 使用nextTick确保DOM已更新
  await nextTick()

  // 自动加载足够数据填满屏幕
  console.log('自动加载足够数据填满屏幕')
  await loadEnoughData()
}

const handleChange = (tag, checked) => {
  dataList.value = []
  console.log(tag, checked)
}

const total = ref(0)
// 增加初始页大小，确保能加载更多数据
const searchParams = reactive({
  current: 1,
  pageSize: 12, // 增加初始页大小
  searchText: '',
  sortField: 'create_time',
  sortOrder: 'descend',
})

// 加载图片数据 当 isLoadMore = false 时（默认情况）：表示初始加载，会直接 替换 数据列表：
const pullPagesVO = async (isLoadMore = false) => {
  // 防止重复加载
  if ((fetchingMore.value && isLoadMore) || !canLoadMore.value) {
    return
  }

  if (isLoadMore) {
    fetchingMore.value = true //设置为正在加载数据
  } else {
    loading.value = true
  }

  //转换搜索参数
  const params = {
    ...searchParams,
    tags: [],
  }

  if (selectedCategory.value !== 'all') {
    params.category = selectedCategory.value
  }

  selectedTags.value.forEach((useTag, index) => {
    if (useTag) {
      params.tags.push(tagList.value[index])
    }
  })

  try {
    const res = await getPicturePageVOs(params)
    if (res.data.code === 0 && res.data.data) {
      const data = res.data.data

      if (isLoadMore) {
        // 追加新数据
        dataList.value = [...dataList.value, ...data.records]
      } else {
        // 初始加载
        dataList.value = data.records
      }

      total.value = data.total

      // 判断是否还有更多数据
      if (dataList.value.length >= data.total) {
        canLoadMore.value = false
      } else {
        // 增加页码，准备下一次加载
        searchParams.current++
      }
    } else {
      message.error(res.data?.message)
    }
  } catch (e) {
    message.error(e.message)
  } finally {
    loading.value = false
    fetchingMore.value = false
  }
}

// 设置无限滚动
const setupInfiniteScroll = () => {
  if (containerRef.value) {
    // 添加调试日志
    console.log('设置无限滚动监听')

    // 使用window作为滚动容器，这样即使内容不够长也能触发
    const cleanup = useInfiniteScroll(
      window,
      async () => {
        // 计算容器底部与视口底部的距离
        const rect = containerRef.value.getBoundingClientRect()
        // 当容器底部接近视口底部时触发加载
        if (rect.bottom - window.innerHeight < 100) {
          console.log('触发加载更多数据')
          await pullPagesVO(true) // 加载更多数据
        }
      },
      {
        distance: 100, // 增加触发距离
        throttle: 500, // 增加节流时间
        direction: 'bottom', // 明确指定方向
      },
    )

    return cleanup
  }
}

// 自动加载足够数据填满屏幕
const loadEnoughData = async () => {
  if (!containerRef.value || !canLoadMore.value) return

  console.log('开始加载足够数据填满屏幕...')
  let iterations = 0
  const maxIterations = 5 // 防止无限循环

  // 获取视口高度
  const windowHeight = window.innerHeight

  // 持续加载直到填满屏幕或没有更多数据
  while (iterations < maxIterations && canLoadMore.value) {
    iterations++
    console.log(`自动加载第${iterations}次数据`)

    // 加载更多数据
    await pullPagesVO(true)

    // 使用nextTick确保DOM更新后再计算高度
    await nextTick()

    // 获取容器实际高度
    const containerHeight = containerRef.value.getBoundingClientRect().height
    console.log(`当前容器高度: ${containerHeight}, 视口高度: ${windowHeight}`)

    // 如果容器高度已超过视口高度的1.5倍，则停止加载
    if (containerHeight >= windowHeight * 1.5) {
      console.log('数据已足够填满屏幕，停止加载')
      break
    }
  }

  console.log(`自动加载完成，总共加载${iterations}次`)
}

onMounted(async () => {
  // 添加调试日志
  console.log('组件挂载完成')
  //获取分类还有标签
  await getTagsCate()
  // 初始加载第一页数据
  await pullPagesVO()

  // 使用nextTick确保DOM已更新
  await nextTick()

  // 自动加载足够数据填满屏幕
  console.log('自动加载足够数据填满屏幕')
  await loadEnoughData()

  // 数据加载完成后设置无限滚动
  console.log('数据加载完成，设置无限滚动')
  setupInfiniteScroll()
})
</script>
<style scoped>
.homeview {
  background: none;
  background-color: transparent !important;
  width: 100%;
  height: fit-content;
}

/* 自定义Tabs组件样式 */
.homeview :deep(.ant-tabs-tab) {
  /*background: linear-gradient(135deg, #00ebff 0%, #00ebff 20.32%, #8972ff 80.02%, #ae8dff 100%)*/
  color: rgba(255, 255, 255, 0.85) !important; /* 未选中标签的文字颜色 */
}

.homeview :deep(.ant-tabs-tab-active) .ant-tabs-tab-btn {
  color: #1890ff !important; /* 选中标签的文字颜色 */
}

.homeview :deep(.ant-tabs-ink-bar) {
  background-color: #1890ff !important; /* 下划线颜色 */
}

.card_img {
  border-radius: 20px;
}

.roleimg {
  cursor: pointer;
  border-radius: 5px;
  background-color: white;
}

.roleimg:hover {
  transition: 0.3s;
  box-shadow: 0 0 20px #9e9ec9;
}

.tagdisplay {
  display: flex;
  flex-wrap: wrap; /* 允许标签换行 */
  gap: 5px; /* 标签之间的间距 */
  font-size: 3px;
}

.description {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制显示行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5; /* 配合max-height计算行数 */
  max-height: calc(1.5em * 3); /* 3行高度（1.5行高×3行） */
  text-overflow: ellipsis;
}

.pictureName {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制显示行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.5; /* 配合max-height计算行数 */
  max-height: calc(1.5em * 2); /* 3行高度（1.5行高×3行） */
  text-overflow: ellipsis;
}

.waterfall-container {
  background: none;
  background-color: transparent;
  //min-height: calc(100vh - 100px); /* 增加最小高度 */
  position: relative;
  padding-bottom: 60px; /* 增加底部空间 */
  width: 100%;
  margin-top: -20px;
  overflow: visible; /* 确保内容可以溢出以便滚动 */
}

.loading-indicator {
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 14px;
}

.ant-tag {
  font-size: 10px;
}

.waterfall-container :deep(.ant-spin-dot-item) {
  background-color: yellow !important;
}

.end-message {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}
/* 调整分类的按钮样式 */
.homeview :deep(.ant-tabs-tab-btn .btn-primary:hover) {
  box-shadow: 0 0 15px #fdfdfd;
  transition: 0.3s;
}

.homeview :deep(.ant-tag-checkable) {
  border-radius: 20px;
  background-color: #5c6896;
  color: white;
  font-size: 1rem;
  box-sizing: content-box;
  padding: 6px 12px 6px 12px;
}

.homeview :deep(.ant-tag-checkable.ant-tag-checkable-checked) {
  transition: 0.3s;
  background-color: blueviolet;
  box-shadow: 0 0 10px white;
}

.searchField {
  width: 90%;
}
@media (min-width: 768px) {
  .searchField {
    width: 30%;
  }
}
</style>
